// App.js
import React, {useState} from 'react'

const App = () => {
  const [persons, setPersons] = useState([
    { name: 'Arto Hellas', number: '040-123456', id: 1}
  ]) 
  const [newName, setNewName] = useState('')
  const [newNumber, setNewNumber] = useState('')

  const containsPerson = (persons, newName) => 
    persons.some((person) => person.name === newName)
  
  const numberofPersons = persons.length;

  const addPerson = (event) => {
    event.preventDefault()
    const contains = containsPerson(persons,newName)
    console.log(contains)
    if (contains) {
      alert(`${newName} already in phonebook`)
      return
    }
    const personObject = {
      id: numberofPersons + 1,
      name: newName,
      number: newNumber,
    }
    setPersons(persons.concat(personObject))
    setNewName('')
    setNewNumber('')
  }

  const handleNameChange = (event) => {
    setNewName(event.target.value)
  }

  const handleNumberChange = (event) => {
    setNewNumber(event.target.value)
  }

  return (
    <div>
      <h2>Phonebook</h2>
      <form onSubmit={addPerson}>
        <div>
          name: <input value={newName} onChange={handleNameChange}/>
        </div>
        <div>number: <input value={newNumber} onChange={handleNumberChange}/></div>
        <div>
          <button type="submit">add</button>
        </div>
      </form>
      <h2>Numbers</h2>
      {persons.map(person => 
        <p key={person.id}>{person.name} {person.number}</p>  
      )}
    </div>
  )
}

export default App

// index.js
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(
  <App/>,
  document.getElementById('root')
)